<template>
  <div>
    <!--    面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片-->
    <el-card>
      <!-- 搜索-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.keyWord" clearable @clear="btnClear">
            <el-button slot="append" icon="el-icon-search" @click="btnSearch"></el-button>
          </el-input>
        </el-col>
        <el-col :span="13">
          <el-button type="primary" @click="addUserdialogVisible=true">添加用户</el-button>
          <el-button @click="uploadBanner" type="primary" style="margin-left: 20px;">上传banner<i
              class="el-icon-upload el-icon--right"></i></el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 start-->
      <el-table
          :data="userList"
          style="width: 100%"
          border stripe>
        <el-table-column type="index" width="50" label="#"></el-table-column>
        <el-table-column
            prop="username"
            label="用户名"
            width="180">
        </el-table-column>
        <el-table-column
            prop="email"
            label="邮箱"
            width="180">
        </el-table-column>
        <el-table-column
            prop="state"
            label="状态" width="160">
          <template v-slot="scope">
            <el-switch
                v-model="scope.row.state"
                active-color="#13ce66"
                inactive-color="#ff4949" @change="stateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="创建时间"
            width="180">
          <template v-slot="scope">
            {{ scope.row.createTime | fmtdate }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-tooltip class="item" effect="dark" content="修改" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" circle @click="showEditDialog(scope.row.id)"></el-button>
              >
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" circle @click="delUser(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" circle @click="allotRoleClic(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 用户列表 end-->
      <!--分页-->
      <el-pagination background
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pageNum"
                     :page-sizes="[5, 10, 15, 20]"
                     :page-size="queryInfo.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </el-card>
    <!--增加用户box-->
    <el-dialog
        title="添加用户"
        :visible.sync="addUserdialogVisible"
        width="50%" @close="addDialogClose">
      <el-form :model="ruleForm" :rules="rules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
         <el-button @click="addUserdialogVisible = false">取 消</el-button>
         <el-button type="primary" @click="addSubmitForm('addFormRef')">确 定</el-button>
      </span>
    </el-dialog>
    <!--修改用户box-->
    <el-dialog
        title="修改用户"
        :visible.sync="editUserdialogVisible"
        width="50%" @close="editDialogClose">
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户编号">
          <el-input readonly v-model="editForm.id"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="username">
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="editForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
         <el-button @click="editUserdialogVisible = false">取 消</el-button>
         <el-button type="primary" @click="editSubmitForm('editFormRef')">确 定</el-button>
      </span>
    </el-dialog>
    <!--分配角色-->
    <el-dialog
        title="分配角色"
        :visible.sync="setRoledialogVisible"
        width="40%">
      <div class="allotrole">
        <div>用户名称：{{ admin.username }}</div>
        <div>用户角色：{{ admin.role ? admin.role.rolename : '暂无角色' }}</div>
        <div>分配角色：
          <el-select v-model="roleId" placeholder="请选择">
            <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.rolename"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
         <el-button @click="setRoledialogVisible = false">取 消</el-button>
         <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 上传图片弹出框 -->
    <el-dialog :visible.sync="upLoadVisible" title="上传图像" width="50%">
      <el-form v-model="uploadForm"  ref="uploadForm" label-width="120px" :rules="rules">
        <el-form-item label="主标题:">
          <el-input placeholder="主标题" v-model="uploadForm.username" style="width: 194px;"></el-input>
        </el-form-item>
        <el-form-item label="密码:">
          <el-input type="password" placeholder="密码" v-model="uploadForm.password" style="width: 194px;"></el-input>
        </el-form-item>
        <el-upload
            ref="upload"
            action=""
            drag
            :limit=1
            :multiple="false"
            :http-request="uploadFile"
            :auto-upload="false">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传图片文件，且只能上传一张</div>
        </el-upload>
        <el-form-item>
          <el-button size="small" type="primary" @click="addPic">立即上传</el-button>
          <el-button size="small" @click="upLoadVisible=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "UserList",
  data() {
    //验证邮箱
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z])+/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error("请输入合法的邮箱"))
    }
    return {
      userList: [],//存储用户列表
      queryInfo: { //分页查询条件
        keyWord: '', //模糊查询用户名
        pageNum: 1, //当前页码
        pageSize: 5 //每页数量
      },
      total: 0, //用户总记录
      addUserdialogVisible: false, //增加用户框是否显示
      editUserdialogVisible: false, //修改用户框是否显示
      setRoledialogVisible: false,//显示分配角色对话框
      //绑定添加表单数据
      ruleForm: {
        username: '',
        password: '',
        email: ''
      },
      //绑定修改表单数据
      editForm: {},
      //验证规则
      rules: {
        username: [
          {required: true, message: '请输入用户名称', trigger: 'blur'},
          {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入用户密码', trigger: 'blur'},
          {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入用户邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ]
      },
      admin: {},//待分配角色的用户
      roleList: [],//角色列表
      roleId: '',//要分配的新的角色id
      upLoadVisible: false,//上传兑换框，默认不显示
      uploadForm: {
        //主标题
        username: '',
        password:''
      },
    }
  },
  created() {
    this.getUserList();
  },
  methods: {
    //获取用户列表
    async getUserList() {
      const {data: res} = await this.$axios.get("/admin/list", {params: this.queryInfo})
      if(res.code!='0'){
        return this.$message.error(res.msg)
      }
      this.userList = res.data.records
      this.total = res.data.total
    },
    //当前页码
    handleCurrentChange(pageNum) {
      this.queryInfo.pageNum = pageNum;
      this.getUserList()
    },
    //每页数量
    handleSizeChange(pageSize) {
      this.queryInfo.pageSize = pageSize
      this.getUserList()
    },
    //用户名模糊搜索
    btnSearch() {
      console.log(this.queryInfo);
      this.getUserList()
    },
    //清空搜索框
    btnClear() {
      this.getUserList()
    },
    //修改状态
    async stateChange(userInfo) {
      const {data: res} = await this.$axios.put('admin/update/' + userInfo.id + '/state/' + userInfo.state)
      if (res.code != '0') return this.$message.error(res.msg)
      this.$message.success(res.msg)
    },
    //关闭添加窗口，清空表单
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    //关闭添加窗口，清空表单
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    //添加用户
    addSubmitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const {data: res} = await this.$axios.post("admin/add", this.ruleForm)
          if (res.code != '0') return this.$message.error(res.msg) //添加失败
          this.$message.success(res.msg) //添加成功
          this.addUserdialogVisible = false  //关闭添加窗口
          this.getUserList()//刷新数据
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //显示修改用户对话框
    async showEditDialog(userid) {
      console.log(userid);
      const {data: res} = await this.$axios.get("admin/get/" + userid)
      console.log(res.data);
      this.editForm = res.data
      this.editUserdialogVisible = true
    },
    //提交修改用户数据
    editSubmitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const {data: res} = await this.$axios.put("admin/update", this.editForm)
          if (res.code != '0') return this.$message.error(res.msg) //修改失败
          this.$message.success(res.msg) //修改成功
          this.editUserdialogVisible = false  //关闭修改窗口
          this.getUserList()//刷新数据
        } else {
          console.log('修改失败!!');
          return false;
        }
      });
    },
    //删除用户
    delUser(userid) {
      this.$confirm('您将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data: res} = await this.$axios.delete("/admin/del/" + userid)
        if (res.code != '0') return this.$message.error(res.msg)
        this.getUserList()
        this.$message.success(res.msg)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //显示分配角色对话框
    async allotRoleClic(admin) {
      const {data: res} = await this.$axios.get("role/roleList")
      this.roleList = res.data
      this.admin = admin;
      this.setRoledialogVisible = true
    },
    //保存新的角色
    async saveRole() {
      const {data: res} = await this.$axios.put(`admin/allotrole/${this.admin.id}/${this.roleId}`)
      if (res.code != '0') {
        return this.$message.error("授权失败")
      }
      this.$message.success("分配权限成功")
      this.getUserList();
      this.setRoledialogVisible=false
    },
    uploadBanner () {
      this.upLoadVisible = true
    },
    //默认上传：this.$refs.upload.submit()  el-upload自带submit方法
    //自定义上传文件
    //http-request	覆盖默认的上传行为，可以自定义上传的实现	function
    uploadFile(params){
      console.log("030303")
      // 根据后台需求数据格式
      const  form=new FormData();
      // 文件对象
      form.append("file", params.file);
      // 要在请求时添加特定属性（其他参数），所以要用自己方法覆盖默认的action
      console.log(JSON.stringify(this.uploadForm));
      form.append("admin", JSON.stringify(this.uploadForm));
      this.$axios.post("admin/upload",form).then((result)=>{
        console.log(result);
        if(result.data.code==='0'){
          this.$message.success(result.data.msg);
          this.upLoadVisible=false;
        } else {
          this.$message.warning(result.data.msg);
        }
        //上传完成后，清空缓存
        this.$refs.upload.clearFiles();
        this.$refs.uploadForm.resetFields();

      }).catch((error)=>{
        console.log("上传失败 file：",params);
        //即使失败，也会清除上传的图片，因为只有上传图片的动作发生时，他才会调用上传接口
        this.$refs.upload.clearFiles();
        this.$message.warning(error.message);
      })
    },
    addPic(){
      this.$refs.upload.submit()
    }
  }
}
</script>

<style scoped>
.el-card {
  margin-top: 15px;
}

.el-table, .el-pagination {
  margin-top: 15px;
}
</style>